package cn.gcjxsc.service.worker;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author pumbaa
 * @since 1.2
 */
public abstract class SingleWorker implements Runnable {
    protected Logger logger = LoggerFactory.getLogger(SingleWorker.class);
    protected boolean isExist = false;

    public void start(){
        Thread thread = new Thread(this);
        thread.start();
    }

    public synchronized void stop(){
        System.out.println("stop .......");
        this.isExist = true;
        this.notifyAll();
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        while(!isExist) {
            try {
                doBusiness();
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(getClass().getName() + ":{}", e.getMessage());
            }
        }
    }

    protected abstract void doBusiness() throws Exception;
}
